package com.aspire.moss.portal.desktop;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;

import com.aspire.moss.portal.R;

/**
 * 第一页的应用
 * 
 * @author Administrator
 * 
 */
public class CellLayout extends ViewGroup implements CellLayoutController {

    private static final String TAG = "CellLayout";

    private static final int MOVE_ICON_TIME = 250;

    private int mWidth, mHeight;// 控件的宽度,高度

    public int page_no;// 屏幕id

    private float clos, rows; // 当前页能显示的行数和列数

    private int cellWidth, cellHeight;// 每个子控件应该占的高度与宽度,但是控件要排在这个宽度中间的

    private float mCellWidth, mCellHeight;// 每个了控件的实际高度与宽度

    private static final int DEL_VIEW = 0;

    private static final int DEL_MOVE = 1;

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case DEL_VIEW:
                removeViewAt(msg.arg1);
                break;
            case DEL_MOVE:
                if (null != msg.obj && msg.obj instanceof Boolean) {
                    clearUp(msg.arg1, msg.arg2, true);
                } else {
                    clearUp(msg.arg1, msg.arg2, false);
                }
                break;
            }

            super.handleMessage(msg);
        }

    };

    Context mContext;

    public CellLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CellLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout);
        clos = a.getInt(R.styleable.CellLayout_clos, 4);
        rows = a.getInt(R.styleable.CellLayout_rows, 4);
        mCellWidth = a.getDimension(R.styleable.CellLayout_cellWidth, 80);
        mCellHeight = a.getDimension(R.styleable.CellLayout_cellHeight, 80);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidth = MeasureSpec.getSize(widthMeasureSpec);
        mHeight = MeasureSpec.getSize(heightMeasureSpec);

        final int mpmWidth = (int) (mWidth - getPaddingLeft() - getPaddingRight());
        final int mpmHeight = (int) (mHeight - getPaddingTop() - getPaddingBottom());

        cellWidth = (int) (mpmWidth / clos);
        cellHeight = (int) (mpmHeight / rows);
        View child = null;
        for (int i = 0; i < getChildCount(); i++) {
            child = getChildAt(i);
            final int childWidth = MeasureSpec.makeMeasureSpec((int) mCellWidth, MeasureSpec.EXACTLY);
            final int childHeigth = MeasureSpec.makeMeasureSpec((int) mCellHeight, MeasureSpec.EXACTLY);
            child.measure(childWidth, childHeigth);
        }
        setMeasuredDimension(resolveSize(mWidth, widthMeasureSpec), resolveSize(mHeight, heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d(TAG, "onLayout page_no =" + page_no + " getChildCount=" + getChildCount());
        AppView child = null;
        AppInfo info = null;
        int pos_no = 0;
        int left = 0;
        int top = 0;
        for (int i = 0; i < getChildCount(); i++) {
            child = (AppView) getChildAt(i);
            info = child.appInfo;
            pos_no = child.appInfo.pos_no;
            left = (int) getMChildLeft(pos_no);
            top = (int) getMChildTop(pos_no);
            child.layout(left, top, (int) (left + mCellWidth), (int) (top + mCellHeight));
        }

    }

    public float getMChildTop(int pos_no) {
        int cellY = (pos_no / (int) clos);
        boolean is = pos_no % clos == 0 ? true : false;
        if (is) {
            cellY -= 1;
        }
        return cellY * cellHeight + getPaddingTop() + (cellHeight - mCellHeight) / 2;
    }

    public float getMChildLeft(int pos_no) {
        int cellX = pos_no % (int) clos;
        if (cellX > 0) {
            cellX -= 1;
        } else {
            cellX = (int) clos - 1;
        }
        return cellX * cellWidth + getPaddingLeft() + (cellWidth - mCellWidth) / 2;
    }

    /**
     * 是否还有空位
     * 
     * @return
     */
    public boolean isEmpty() {
        return getChildCount() == 0 ? true : false;
    }

    /**
     * 根据当前的X , Y 值找出当前的地方应用图标
     * 
     * @param x
     * @param y
     * @return
     */
    public View isExists(int x, int y, int width, int height) {
        final int centerX = x + width / 2;
        final int centerY = y + height / 2;
        View view = null;
        for (int i = 0; i < getChildCount(); i++) {
            view = getChildAt(i);
            if ((view.getLeft() < centerX && view.getTop() < centerY) && (view.getRight() > centerX && view.getBottom() > centerY)) {
                return view;
            }
        }
        return null;
    }

    /**
     * 返回当前的应用的状态,-1 为此应用不存在,其实为View.VISIBLE;View.GONE
     * 
     * @param appInfo
     */
    public int getCellViewStatu(AppInfo appInfo) {
        AppView cellView = null;
        for (int i = 0; i < getChildCount(); i++) {
            cellView = (AppView) getChildAt(i);
            if (appInfo.eqPosScreen(cellView.appInfo)) {
                return cellView.getVisibility();
            }
        }
        return -1;
    }

    /**
     * 此页是否已满
     * 
     * @return
     */
    public boolean isFull() {
        return getChildCount() == clos * rows ? true : false;
    }

    /**
     * 找到最后一个应用的位置 如果返回null则该页没有空位了
     * 
     * @return
     * 
     *         public int[] findLastAppView() { int cell[] = null; if
     *         (isEmpty()) { cell = new int[] { 0, 0 }; } else if (!isFull()) {
     *         int maxX = 0; int maxY = 0; AppInfo info = null; for (int i = 0;
     *         i < getChildCount(); i++) { info = ((AppView)
     *         getChildAt(i)).appInfo; final int infoCellX = info.cellX; final
     *         int infoCellY = info.cellY; Log.i(TAG, "findLastAppview AppInfo="
     *         + info); if (maxY < infoCellY) { maxY = infoCellY; maxX =
     *         infoCellX; } else if (maxY == infoCellY && maxX < infoCellX) {
     *         maxX = infoCellX; } } Log.d(TAG,
     *         "find screenId  max cellXY maxX=" + maxX + " maxY=" + maxY); //
     *         找到最大的一格了 cell = new int[] { maxX, maxY }; } return cell; }
     */
    /**
     * 找到最后一个空位
     * 
     * @return
     */
    public int[] findLastEmptyAppView() {
        int cell[] = null;
        if (isEmpty()) {
            cell = new int[] { 0, 0 };
        } else if (!isFull()) {
            cell = findLastAppView();
            cell = findViewNext(cell[0], cell[1]);
        }
        return cell;
    }

    /**
     * 删除一个应用
     * 
     * @param appInfo
     * @return
     * 
     *         public boolean removeAppView(final AppInfo appInfo, Animation
     *         scale, int visible) { final int index = findApp(appInfo,
     *         visible); Log.d(TAG, "removeAppView index=" + index + "appinfo="
     *         + appInfo); if (-1 != index) { final View delVew =
     *         getChildAt(index); if (null != scale) {
     *         scale.setAnimationListener(new ViewAnimationListener() {
     * @Override public void onAnimationEnd(Animation animation) {
     *           super.onAnimationEnd(animation);
     *           handler.sendMessage(handler.obtainMessage(DEL_VIEW, index, 0));
     *           handler.sendMessage(handler.obtainMessage(DEL_MOVE,
     *           appInfo.cellX, appInfo.cellY, true)); }
     * 
     *           }); delVew.startAnimation(scale); } else {
     *           handler.sendMessage(handler.obtainMessage(DEL_VIEW, index, 0));
     *           handler.sendMessage(handler.obtainMessage(DEL_MOVE,
     *           appInfo.cellX, appInfo.cellY, false)); }
     * 
     *           } return true; }
     */

    /**
     * 添加一个应用
     * 
     * @param appInfo
     * @return
     * 
     *         public boolean addAppView(AppInfo appInfo){ CellView child =
     *         (CellView)
     *         Utils.getLayoutInflater(mContext).inflate(R.layout.cell, null);
     *         child.appInfo = appInfo; child. addView(child ); return true; }
     */
    /**
     * 当删除一个应用了,整理其它的
     * 
     * @param delXY
     * 
     *            public void clearUp(final int cellX, final int cellY, final
     *            boolean isAnim) { final List<AppView> moves = new
     *            ArrayList<AppView>(); AppView cellView = null; int next[] =
     *            findViewNext(cellX, cellY); if (null != next) { int viewId =
     *            0; while (-1 != (viewId = findApp(next[0], next[1],
     *            View.VISIBLE))) { cellView = (AppView) getChildAt(viewId);
     *            next = findViewNext(cellView.appInfo.cellX,
     *            cellView.appInfo.cellY); moves.add(cellView); } for (AppView
     *            view : moves) { moveToPre(view, isAnim); } }
     * 
     *            }
     */
    /**
     * 根据AppInfo找到view的索引
     * 
     * @param appInfo
     * @param visible
     * @return public int findApp(AppInfo appInfo, int visible) { return
     *         findApp(appInfo.cellX, appInfo.cellY, visible); }
     */
    /**
     * 根据appinfo找以view的索引
     * 
     * @param appInfo
     * @return
     * 
     *         private int findApp(int cellX, int cellY, int visible) { AppView
     *         temp = null; for (int i = 0; i < getChildCount(); i++) { temp =
     *         (AppView) getChildAt(i); if (temp.appInfo.cellX == cellX &&
     *         temp.appInfo.cellY == cellY && temp.getVisibility() == visible) {
     *         return i; } } return -1; }
     * 
     *         public View findAppView(AppInfo appInfo, int visible) { return
     *         findAppView(appInfo.cellX, appInfo.cellY, visible); }
     */

    /**
     * 默认查找可视的应用
     * 
     * @param appInfo
     * @return
     * 
     *         public View findAppView(AppInfo appInfo) { return
     *         findAppView(appInfo.cellX, appInfo.cellY, VISIBLE); }
     */
    /**
     * 根据appinfo找出Cellview
     * 
     * @param appInfo
     * @return
     * 
     *         private View findAppView(int cellX, int cellY, int visible) {
     *         final int viewIndex = findApp(cellX, cellY, visible); return
     *         viewIndex != -1 ? getChildAt(viewIndex) : null; }
     */
    /**
     * 两个应用交换位置
     * 
     * @param appInfo1
     * @param appInfo2
     * @return
     */
    public boolean swapAppView(AppInfo appInfo1, AppInfo appInfo2) {

        return true;
    }

    /**
     * 返回上一个应用的cellx ,cellY
     * 
     * @param cellX
     * @param cellY
     * @return
     */
    public int[] findViewPro(int cellX, int cellY) {
        int fCellX = 0;
        int fCellY = 0;
        if (cellX == 0 && cellY == 0) {
            return null;
        } else {
            if (cellX == 0) {
                fCellX = (int) (clos - 1);
                fCellY = cellY - 1;
            } else {
                fCellX = cellX - 1;
                fCellY = cellY;
            }
        }
        return new int[] { fCellX, fCellY };
    }

    /**
     * 查找下一个
     * 
     * @param cellX
     * @param cellY
     * @return
     */
    public int[] findViewNext(int cellX, int cellY) {
        int fCellX = 0;
        int fCellY = 0;
        if (cellX == clos && cellY == rows) {
            return null;
        } else if (cellX != clos - 1) {
            fCellX = cellX + 1;
            fCellY = cellY;
        } else {
            fCellY = cellY + 1;
        }
        return new int[] { fCellX, fCellY };
    }

    @Override
    public int[] findLastAppView() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean removeAppView(AppInfo appInfo, Animation scale, int visible) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void clearUp(int cellX, int cellY, boolean isAnim) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageNoChange(int page_no) {
        if (this.page_no != page_no) {
            this.page_no = page_no;
        }
    }

    /**
     * 移动到哪个
     * 
     * @param cellView
     * @param cellX
     * @param cell
     * 
     *            public void moveToXY(final AppView cellView, final int cellX,
     *            final int cellY, boolean isAnim) { if (!isAnim) {
     *            resetCellView(cellView, cellX, cellY); } else { Animation
     *            animation = new TranslateAnimation(0.0f, getMChildLeft(cellX)
     *            - cellView.getLeft(), 0.0f, getMChildTop(cellY) -
     *            cellView.getTop()); animation.setDuration(MOVE_ICON_TIME);
     *            animation.setAnimationListener(new ViewAnimationListener() {
     * @Override public void onAnimationEnd(Animation animation) {
     *           super.onAnimationEnd(animation); resetCellView(cellView, cellX,
     *           cellY); }
     * 
     *           }); animation.setFillEnabled(true);
     *           cellView.startAnimation(animation); }
     * 
     *           }
     */

    /**
     * 把应用向下一个移动
     * 
     * @param cellView
     * 
     *            public void moveToNext(AppView cellView, boolean isAnim) { if
     *            (null != cellView && null != cellView.appInfo) { AppInfo
     *            appInfo = cellView.appInfo; int[] nextPoint =
     *            findViewNext(appInfo.cellX, appInfo.cellY); if (null !=
     *            nextPoint) { moveToXY(cellView, nextPoint[0], nextPoint[1],
     *            isAnim); } } }
     */
    /**
     * 固定应用的位置
     * 
     * @param cellView
     * @param cellX
     * @param cellY
     * 
     *            private void resetCellView(final AppView cellView, final int
     *            cellX, final int cellY) { cellView.appInfo.cellX = cellX;
     *            cellView.appInfo.cellY = cellY; int left = (int)
     *            getMChildLeft(cellX); int top = (int) getMChildTop(cellY);
     *            cellView.layout(left, top, left + cellWidth, top +
     *            cellHeight); }
     */
    /**
     * 把应用向上一个移动
     * 
     * @param cellView
     * 
     *            public void moveToPre(AppView cellView, boolean isAnim) { if
     *            (null != cellView && null != cellView.appInfo) { AppInfo
     *            appInfo = cellView.appInfo; int[] prePoint =
     *            findViewPro(appInfo.cellX, appInfo.cellY); if (null !=
     *            prePoint) { moveToXY(cellView, prePoint[0], prePoint[1],
     *            isAnim); } } }
     */

}
